package com.gitee.dfdiot.sdk.utils.signs;

import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author HuYong
 * @date 2022/6/7
 */
public class SignUrlUtil {

    private final static String CHARSET_UTF8 = "utf8";

    /**
     * 将排序后的参数生成
     * @param sortParam
     * @param isEncodeKV
     * @return
     */
    public static String generateQueryString(TreeMap<String,String> sortParam, boolean isEncodeKV){
        StringBuilder stringBuilder = new StringBuilder();
        for(Map.Entry<String,String> entry : sortParam.entrySet()){
            if(isEncodeKV){
                stringBuilder.append(percentEncode(entry.getKey())).append("=").append(percentEncode(entry.getValue())).append("&");
            }else{
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        if(stringBuilder.length() > 1){
            stringBuilder.setLength(stringBuilder.length() - 1);
        }
        return stringBuilder.toString();
    }

    /**
     * 编码符号转换
     * @param value
     * @return
     */
    public static String percentEncode(String value){
        try {
            return value == null ? null : URLEncoder.encode(value,CHARSET_UTF8)
                    .replace("+","%20")
                    .replace("*","%2A")
                    .replace("%7E","~");
        }catch (Exception e){
        }
        return "";
    }




    /*public static void main(String[] args) {
        System.out.println(percentEncode("SRmL8wUUtHN36J/YWaaEgBlO2CE="));
    }*/

}
